var systemInfo = chrome.experimental.systemInfo;

var indicator = {}
var isStarted = false;

function onStorageChanged(info) {
  var elem = document.getElementById(info.id);
  if (indicator[info.id]++ % 2)
    elem.bgColor = "green";
  else
    elem.bgColor = "white";
  elem.innerHTML = info.availableCapacity;
}

function startMonitor() {
  if (isStarted) return;
  systemInfo.storage.onAvailableCapacityChanged.addListener(onStorageChanged);
  isStarted = true;
}

function stopMonitor() {
  if (!isStarted) return;
  systemInfo.storage.onAvailableCapacityChanged.removeListener(
      onStorageChanged);
  isStarted = false;
}

function showStorageInfo(unit) {
  table = "<tr><td>" + unit.id + "</td>" +
    "<td>" + unit.type + "</td>" +
    "<td>" + Math.round(unit.capacity/1024) + "</td>" +
    "<td id=" + "\"" + unit.id + "\">" +
    Math.round(unit.availableCapacity/1024) +
    "</td></tr>\n";
  return table;
}

var cpuChart;
var memoryChart;

function init() {
//	document.getElementById("start-btn").onclick = startMonitor;
//	document.getElementById("stop-btn").onclick = stopMonitor;

	// Get CPU information.
	chrome.experimental.systemInfo.cpu.get(function(cpu) {
		cpuCharInit(cpu);
	});
	chrome.experimental.systemInfo.cpu.onUpdated.addListener(function(info) {
		setMemoryInfo(false);
		cpuCharUpdate(info);
	});
	
	setMemoryInfo(true);
  
	// Get storage information.
	/*
	chrome.experimental.systemInfo.storage.get(function(units) {
		var table = "<table width=65% border=\"1\">\n" +
		"<tr><td><b>ID</b></td>" +
		"<td><b>Type</b></td>" +
		"<td><b>Total Capacity (KB)</b></td>" +
		"<td><b>Available Capacity (KB)</b></td>" +
		"</tr>\n";
		for (var i = 0; i < units.length; i++) {
			indicator[units[i].id] = 0;
			table += showStorageInfo(units[i]);
		}
		table += "</table>\n";
		var div = document.getElementById("storage-list");
		div.innerHTML = table;
	});
	*/
}

function setMemoryInfo(initFlag) {
	chrome.experimental.systemInfo.memory.get(function(memory) {
//		var memoryInfo =
//		"<b>Total Capacity:</b> " + Math.round(memory.capacity / 1024) + "KB" +
//		"<br><b>Available Capacity: </b>" +
//		Math.round(memory.availableCapacity / 1024) + "KB"
//		var div = document.getElementById("memory-info");
//		div.innerHTML = memoryInfo;
		if(initFlag) {
			memoryChartInit(memory);
		} else {
			memoryChartUpdate(memory);
		}
	});
}

function memoryChartInit(memory) {
	var totalMega = Math.round(memory.capacity/(1024*1024));
	var useMega = Math.round((memory.capacity - memory.availableCapacity)/(1024*1024));
	var availMega = Math.round(memory.availableCapacity/(1024*1024));
	var availPercent = Math.round((memory.availableCapacity)/memory.capacity*100);
	var usePercent = 100-availPercent;
	console.log("memoryChartInit");
	memoryChart = new Highcharts.Chart({
        chart: {
            renderTo: 'memoryContainer',
            type: 'bar'
        },
        title: {
            text: 'Memory Resource Monitor'
        },
        xAxis: {
            categories: ['Memory']
        },
        yAxis: {
            min: 0,
            max : totalMega,
            title: {
                text: 'Use Capacity(MB)'
            }
        },
        legend: {
            backgroundColor: '#FFFFFF',
            reversed: true
        },
        tooltip: {
            formatter: function() {
            	 return ''+
                 this.series.name +': '+ this.y +'MB';
            }
        },
        plotOptions: {
        	bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
        series: 
        [
            {
            	name: 'Use',
            	data: [useMega]
            }
	    ]
    });
}

function cpuCharInit(cpuInfo) {
	cpuChart = new Highcharts.Chart({
        chart: {
            renderTo: 'cpuContainer',
            type: 'bar'
        },
        title: {
            text: 'CPU Resource Monitor'
        },
        subtitle: {
            text: cpuInfo.modelName
        },
        xAxis: {
            categories: ['core'],
            title: {
                text: null
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: 'CPU Use (%)',
                align: 'high'
            },
            max : 100,
            labels: {
                overflow: 'justify'
            }
        },
        tooltip: {
            formatter: function() {
                return ''+
                    this.series.name +': '+ this.y +'%';
            }
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -100,
            y: 100,
            floating: true,
            borderWidth: 1,
            backgroundColor: '#FFFFFF',
            shadow: true
        },
        credits: {
            enabled: false
        }
    });
	var myJSONObject = {
			"series": [
			           {
			        	   name: 'core',
			        	   data: [0]
			           }
			           ]
	};
	
	for(var i = 0; i < cpuInfo.numOfProcessors; i++) {
		var jsonTemp = {
				name:"core-"+(i+1),
				data: [0]
		}
		myJSONObject.series[i] = jsonTemp;
		cpuChart.addSeries(jsonTemp);
	}
}

function memoryChartUpdate(memory) {
	var totalMega = Math.round(memory.capacity/(1024*1024));
	var useMega = Math.round((memory.capacity - memory.availableCapacity)/(1024*1024));
	var availMega = Math.round(memory.availableCapacity/(1024*1024));
	var availPercent = Math.round((memory.availableCapacity)/memory.capacity*100);
	var usePercent = 100-availPercent;
	memoryChart.series[0].data[0].y = useMega;
	memoryChart.series[0].redraw();
}

function cpuCharUpdate(cpuInfo) {
	for (var i = 0; i < cpuInfo.usagePerProcessor.length; i++) {
		cpuChart.series[i].data[0].y = Math.round(cpuInfo.usagePerProcessor[i]);
		cpuChart.series[i].redraw();
	}
}

document.addEventListener('DOMContentLoaded', init);